<template>
  <el-card>
    <div slot="header">
      <h3>修改品类</h3>
    </div>
    <div>
      <el-row
        class="btn-action-wrap"
        type="flex"
        justify="end"
      >
        <el-button
          type="text"
          size="large"
          @click="handleSeniorLinked"
        >高级关联</el-button
        >
        <el-button
          type="text"
          size="large"
          @click="handleGoodsLinked"
        >关联商品</el-button
        >
        <el-button
          type="text"
          size="large"
          :disabled="tableInfo.selection.length === 0"
          @click="handleCategoryLinked"
        >关联品类</el-button
        >
        <el-button
          v-if="canOpeState"
          type="text"
          size="large"
          :disabled="tableInfo.list.length === 0"
          :loading="btnLoading.submit"
          @click="handleSubmitData"
        >提交</el-button
        >
      </el-row>
    </div>
    <SkusTable
      showSelectCol
      :defaultMinWidth="120"
      :loading="tableInfo.loading"
      :columns="tableInfo.columns"
      :dataSource="tableInfo.list"
      :selectionChange="handleSelectionChange"
      @visibleChange="handleRefreshClassificationInfo"
      @selectChange="handleSelectClassification"
      @handleCancelSelect="handleRemoveRow"
    />
    <!-- 高级关联弹框 -->
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="getSeniorResultFn"
    />
    <!-- 关联商品弹框 -->
    <GoodsLinkedDialog
      :visible.sync="goodsLinked.visible"
      @getSelectRows="getSelectGoodsRowsFn"
    />
    <!-- 关联分类弹框 -->
    <basic-dialog
      title="关联四级类"
      width="60%"
      :visible="categoryLinked.visible"
      :show-close="false"
      :showFooter="false"
    >
      <CategorySelect
        @submitConcat="handleCategoryOk"
        @cancelConcat="handleCategoryClose"
      />
    </basic-dialog>
    <!-- 错误提醒弹框 -->
    <ErrorMessageDialog
      title="错误提醒"
      :visible.sync="errMessage.visible"
      :codeList="errMessage.codeList"
      :handleCancel="handleErrorMessageClose"
      :handleOk="handleErrorMessageOk"
    />
  </el-card>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import BasicDialog from '@/components/BasicDialog';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import CategorySelect from './components/CategorySelect';
import SkusTable from '@/components/skusTable';
import ErrorMessageDialog from '@/components/ErrorMessageDialog';
import GoodsLinkedDialog from './components/GoodsLinkedDialog';
import { tableColumns, showErrMsgColumns, CLASSIFICATION_OPTIONS_NAME } from './constants';
import { MODIFY_CATEGORY } from '@/constants/exportAmountLimit';
import { isResponseSuccess, isResponseSuccessState } from '@/utils/bizUtils';
import { getCanOpeState } from '@/utils/getUtils';
export default {
  components: {
    BasicDialog,
    SkusTable,
    SeniorLinkedDialog,
    CategorySelect,
    ErrorMessageDialog,
    GoodsLinkedDialog
  },
  data () {
    return {
      canOpeState: true, // 页面可操作状态
      seniorLinked: {
        visible: false,
        columns: [{
          label: 'SPU编码',
          prop: 'spuNo',
          type: 'textarea'
        }],
        dataSource: [{ spuNo: '' }],
        existSpuNos: [],
        globalSpuNos: []
      },
      goodsLinked: {
        visible: false,
        globalSpuNos: []
      },
      categoryLinked: {
        visible: false,
      },
      errMessage: {
        visible: false,
        codeList: ''
      },
      tableInfo: {
        list: [], // 表格数据
        columns: tableColumns, // 表格columns
        selection: [], // 勾选列表
        loading: false // 表格加载loading
      },
      btnLoading: {
        submit: false
      },
      uniqueKey: 'spuNo', // 表格数据的唯一标识key名称
      apiObj: {
        getSpuList: { // 查询SPU信息(获取表格数据)
          url: '/sysback/modifySpuCategory/getSpuList',
          type: 'post'
        },
        categoryCommit: { // 单据提交
          url: '/sysback/modifySpuCategory/commit',
          type: 'post'
        },
        getBelongingDeptList: { // 归属部门查询
          url: '/sysback/srm/getBelongingDeptList',
          type: 'post'
        },
        getByCategoryUuid: { // 归类信息查询
          url: '/sysback/classification/getByCategoryUuid',
          type: 'get'
        },
        getCateInfo: { // 查询品类及归类信息
          url: '/sysback/modifySpuCategory/getCateInfo',
          type: 'get'
        }
      }
    };
  },
  mounted () {
    this.setCanOpeState()
  },
  methods: {
    // 设置页面是否可操作状态值
    async setCanOpeState () {
      this.canOpeState = await getCanOpeState(this.$route.name)
    },
    // 关联品类
    handleCategoryLinked () {
      this.categoryLinked.visible = true;
    },
    // 关联品类弹框-确定
    handleCategoryOk (categoryData) {
      const { categoryUuid } = categoryData;
      this.getCateInfoByUuidFn(categoryUuid);
      this.refreshCategoryPathFn(categoryData);
      this.refreshBelongingDeptNameFn();
      this.categoryLinked.visible = false;
    },
    // 关联品类弹框-关闭
    handleCategoryClose () {
      this.categoryLinked.visible = false;
    },
    // 高级关联
    handleSeniorLinked () {
      const curBtnId = getBtnsId('高级关联');
      sessionStorage.setItem('buttonId', curBtnId);
      this.seniorLinked.visible = true;
    },
    // 高级关联-错误消息弹框-关闭
    handleErrorMessageClose () {
      this.errMessage.visible = false;
    },
    // 高级关联-错误消息弹框-确定(继续筛选)
    handleErrorMessageOk () {
      this.seniorLinked.globalSpuNos.push(...this.seniorLinked.existSpuNos);
      const spuNos = [...new Set(this.seniorLinked.globalSpuNos)];
      if (spuNos.length !== 0) {
        this.getTableDataFn(spuNos);
      }
      this.clearErrMessageStateFn();
      this.clearSeniorStateFn();
      this.handleErrorMessageClose();
    },
    // 关联商品
    handleGoodsLinked () {
      this.goodsLinked.visible = true;
    },
    // 表格勾选
    handleSelectionChange (list) {
      this.tableInfo.selection = list;
    },
    // 提交
    async handleSubmitData () {
      if (this.tableInfo.list.length === 0) {
        this.$message.warning('请关联商品');
        return false;
      }
      if (this.tableInfo.list.length > MODIFY_CATEGORY) {
        this.$message.warning(`当前提交的行数不能超过${MODIFY_CATEGORY}`);
        return false;
      }
      const data = {
        commitParamList: this.tableInfo.list
      };
      const { url, type } = this.apiObj.categoryCommit;
      try {
        this.btnLoading.submit = true;
        const res = await ApiRequest(url, type, data);
        this.btnLoading.submit = false;
        if (!isResponseSuccessState(res.retStatus)) {
          return false;
        }
        const { recordNo, modifiedSpuVoList } = res.retData;
        if (!recordNo) {
          const msg = '存在异常商品，无法提交';
          this.$message.warning(msg);
          this.tableInfo.columns = showErrMsgColumns;
          this.tableInfo.list = this.getProcesscedTableDataFn(modifiedSpuVoList);
          return false;
        }
        this.$message.success('提交成功');
        this.$router.push({ name: 'chageFromManageList' });
      } catch (err) {
        this.btnLoading.submit = false;
      }
    },
    // 获取高级关联结果
    async getSeniorResultFn (spuNos) {
      this.goodsLinked.globalSpuNos = [];
      this.seniorLinked.globalSpuNos.push(...spuNos);
      this.getTableDataFn([...new Set(this.seniorLinked.globalSpuNos)]);
    },
    // 清空高级关联数据
    clearSeniorStateFn () {
      this.seniorLinked.dataSource = [{ spuNo: '' }];
    },
    // 高级关联-错误提醒
    errMessageWarningFn (data) {
      this.errMessage.codeList = data.join(';');
      this.errMessage.visible = true;
    },
    // 高级关联-清空错误消息数据
    clearErrMessageStateFn () {
      this.errMessage.codeList = '';
    },
    // 获取批量关联的商品数据
    getSelectGoodsRowsFn (data) {
      this.seniorLinked.globalSpuNos = [];
      this.goodsLinked.globalSpuNos.push(...data.map(row => row.spuNo));
      this.getTableDataFn([...new Set(this.goodsLinked.globalSpuNos)]);
    },
    // 获取表格数据
    async getTableDataFn (spuNos) {
      if (spuNos.length === 0) {
        this.$message.warning('商品编码不能为空');
        return false;
      }
      const data = { spuNos };
      const { url, type } = this.apiObj.getSpuList;
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(url, type, data);
        this.tableInfo.loading = false;
        if (!isResponseSuccess(res)) {
          return false;
        }
        const { isFail, notExistSpuNos, existSpuNos, spuVoList } = res.retData;
        if (isFail) {
          this.errMessageWarningFn(notExistSpuNos);
          this.seniorLinked.existSpuNos = existSpuNos || [];
          this.seniorLinked.globalSpuNos = this.seniorLinked.globalSpuNos.filter(spuNo => !notExistSpuNos.includes(spuNo));
          return false;
        }
        this.tableInfo.columns = tableColumns;
        this.tableInfo.list = this.getProcesscedTableDataFn(spuVoList);
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 获取处理后的表格数据-生成归类options
    getProcesscedTableDataFn (spuVoList) {
      if (!spuVoList) { return []; };
      return spuVoList.reduce((value, item) => {
        value.push({
          ...item,
          [CLASSIFICATION_OPTIONS_NAME]: [{
            classificationName: item.classificationNameUpdate,
            uuid: item.classificationUuidUpdate
          }]
        })
        return value;
      }, []);
    },
    // 根据关联品类更新所勾选的表格数据的品类树
    refreshCategoryPathFn (categoryData) {
      const { categoryUuid, categoryNo, categoryPath } = categoryData;
      this.tableInfo.selection.forEach(row => {
        const index = this.tableInfo.list.findIndex(item => {
          return row[this.uniqueKey] === item[this.uniqueKey];
        });
        if (index !== -1) {
          this.tableInfo.list[index].categoryUuidUpdate = categoryUuid;
          this.tableInfo.list[index].categoryNoUpdate = categoryNo;
          this.tableInfo.list[index].categoryPathUpdate = categoryPath;
        }
      });
    },
    // 获取请求归属部门接口入参
    getQueryParamListFn () {
      return this.tableInfo.selection.reduce((value, item) => {
        value.push({
          categoryUuid: item.categoryUuidUpdate,
          manageAreaUuid: item.manageAreaUuid
        });
        return value;
      }, []);
    },
    // 根据品类Uuid和管理区域更新表格数据的归属部门
    async refreshBelongingDeptNameFn () {
      const queryParamList = this.getQueryParamListFn();
      const data = { queryParamList };
      const { url, type } = this.apiObj.getBelongingDeptList;
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(url, type, data);
        this.tableInfo.loading = false;
        if (!isResponseSuccess(res)) { return false; }
        this.tableInfo.list.forEach(row => {
          if (this.tableInfo.selection.findIndex(
            item => item.spuNo === row.spuNo
          ) !== -1) {
            const {
              hrDepartmentName, hrDepartmentNumber
            } = this.findMappingBelongingDeptNameFn(row, res.retData);
            row.belongingDeptName = hrDepartmentName;
            row.belongingDeptCode = hrDepartmentNumber;
          }
        });
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 查找对应的归属部门
    findMappingBelongingDeptNameFn (row, retData) {
      const key = row.manageAreaUuid + '_' + row.categoryUuidUpdate;
      if (!retData[key]) {
        return {
          hrDepartmentName: '',
          hrDepartmentNumber: ''
        };
      }
      const data = retData[key][0];
      return data;
    },
    // 根据categoryUuid更新对应的归类信息
    async handleRefreshClassificationInfo (row) {
      if (!row.categoryUuidUpdate) { return false; }
      const data = {}
      const { url, type } = this.apiObj.getByCategoryUuid;
      const apiUrl = `${url}?categoryUuid=${row.categoryUuidUpdate}`;
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(apiUrl, type, data);
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          row[CLASSIFICATION_OPTIONS_NAME] = res.retData;
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 根据关联品类查询品类及归类信息
    async getCateInfoByUuidFn (categoryUuid) {
      const { url, type } = this.apiObj.getCateInfo;
      const apiUrl = `${url}?categoryUuid=${categoryUuid}`;
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(apiUrl, type, {});
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          const { classificationUuid, classificationName, taxCode, taxRate } = res.retData;
          this.tableInfo.selection.forEach(row => {
            row[CLASSIFICATION_OPTIONS_NAME] = [{
              classificationName: classificationName,
              uuid: classificationUuid
            }]
            row.classificationUuidUpdate = classificationUuid;
            row.classificationNameUpdate = classificationName;
            row.taxCodeUpdate = taxCode;
            row.taxRateUpdate = taxRate;
          })
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 下拉选择归类
    handleSelectClassification ({ row, target }) {
      if (!target) { return false; }
      const { classificationName, taxCateNo, taxRate, uuid } = target;
      row.classificationNameUpdate = classificationName;
      row.classificationUuidUpdate = uuid;
      row.taxCodeUpdate = taxCateNo;
      row.taxRateUpdate = taxRate;
    },
    // 删除
    handleRemoveRow ({ row, index }) {
      this.tableInfo.list.splice(index, 1);
      _.remove(this.seniorLinked.globalSpuNos, spuNo => spuNo === row.spuNo);
      _.remove(this.goodsLinked.globalSpuNos, spuNo => spuNo === row.spuNo);
    },
  }
}
</script>
